package com.club325.voicemicroblog.persist;

import java.util.ArrayList;

import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import com.club325.voicemicroblog.database.hibernateutil.HibernateUtil;
import com.club325.voicemicroblog.domain.Focus;

public class FocusControllerImplement implements FocusControllerUtils {

	public FocusControllerImplement() {

	}

	/**
	 * @param UserID
	 * @return java.lang.Boolean
	 */
//	public Boolean FocusOnUser(String UserID,String FocusTarget) {
//		if((UserID == null)||(FocusTarget == null)||
//				(UserID.length() < 5)||(UserID.length() > 12)||
//				(FocusTarget.length() < 5)||(FocusTarget.length() > 12))
//		{
//			return false;
//		}
//		
//		
//		return true;
//	}

	/**
	 * @param SpeakerID
	 * @return java.lang.Boolean
	 */
	public Boolean Forget(Focus focus) {
		if(focus == null)
		{
			return false;
		}
		
		try
		{
			Criteria crit = HibernateUtil.getSession().createCriteria(Focus.class);
			crit.add(Restrictions.eq("Listener", focus.getListener()));
			crit.add(Restrictions.eq("Speaker", focus.getSpeaker()));
			if(crit.list().isEmpty() == true)
				return false;
			
			HibernateUtil.delete(crit.uniqueResult());
			return true;
		}
		catch(Exception e)
		{
			e.printStackTrace();
			return false;
		}
	}

	public Boolean FocusOnUser(Focus focus) {
		if(focus == null)
			return false;
		
		try
		{
			HibernateUtil.add(focus);
			return true;
		}
		catch(Exception e)
		{
			e.printStackTrace();
			return false;
		}
	}

	@SuppressWarnings("unchecked")
	public ArrayList<Focus> getFocusByUserID(String UserID, boolean isSpeaker) {
		if(UserID == null)
			return null;
		
		try
		{
			Criteria crit  = HibernateUtil.getSession().createCriteria(Focus.class);
			if(isSpeaker)
			{
				crit.add(Restrictions.eq("Speaker", UserID));
			}
			else
			{
				crit.add(Restrictions.eq("Listener", UserID));
			}
			crit.addOrder(Order.desc("ModifiedTime"));
			return (ArrayList<Focus>) crit.list();
		}
		catch(Exception e)
		{
			e.printStackTrace();
			return null;
		}
	}

	public boolean deleteFocus(Focus entity) {
		if(entity == null)
			return false;
		try
		{
			HibernateUtil.delete(entity);
			return true;
		}
		catch(Exception e)
		{
			return false;
		}
	}
}